package com.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.ajax.AjaxRes;
import com.common.utils.EncryptUtil;
import com.common.utils.base.Const;
import com.controller.base.BaseController;
import com.entity.Login;
import com.entity.User;
import com.service.LoginService;
import com.service.UserService;

@Controller
@RequestMapping("/bg")
public class BackController extends BaseController<Object>{
	
	@Autowired
	private LoginService loginService;
	@Autowired
	private UserService userService;
	
	@RequestMapping("/index")
	public String index()throws Exception{
		return "index";
	}
	
	@RequestMapping("/login")
	public String login()throws Exception{
		return "pages/login";
	}
	
	@RequestMapping("/login/submit")
	@ResponseBody
	public AjaxRes login(Login login){
		AjaxRes res = new AjaxRes();
		if(login.getPassword() == null || login.getPassword().equals("") 
				|| login.getAccount() == null || login.getAccount().equals("")){
			res.setFailMsg(Const.DATA_FAIL);
			return res;
		}
		String oldPass = login.getPassword();
		login.setPassword(EncryptUtil.encoderBySHA(oldPass));
		if(loginService.countPwd(login) >= 1){
			User user = new User();
			login = loginService.find(login).get(0);
			user.setLoginId(login.getId());
			user.setFileRemark("portrait");
			user.setDetail(true);
			try{
				user = userService.find(user).get(0);
				System.out.println(user);
				String character = user.getUserType();
				if(character.equals("管理员")){
					HttpSession session = getRequest().getSession();
					session.setAttribute("loggedIn", user);
					res.setSucceedMsg(Const.DATA_SUCCEED);
				}else{
					res.setFailMsg("该用户没有权限");
				}
			}catch(Exception e){
				e.printStackTrace();
				res.setFailMsg(Const.DATA_FAIL);
			}
		}else{
			res.setFailMsg("用户不存在或密码错误");
		}
		return res;
	}
	
	
	@RequestMapping("/logout")
	public String logout(){
		getRequest().getSession().setAttribute("loggedIn", null);
		return "pages/login";
	}
	
}
